package com.imooc.example.springtxpa.service;

import com.imooc.example.springtxpa.dao.CustomerRepository;
import com.imooc.example.springtxpa.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ;
import static org.springframework.transaction.TransactionDefinition.PROPAGATION_SUPPORTS;

/**
 * @author linzou@linkdoc.com
 * @ClassName: CustomerServiceInAnnotation
 * @Description:
 * @date 2019/1/1 11:59 AM
 */
@Service
public class CustomerServiceInCode {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    PlatformTransactionManager transactionManager;

    public Customer create(Customer customer){
        TransactionDefinition definition = new DefaultTransactionDefinition();
        ((DefaultTransactionDefinition) definition).setIsolationLevel(ISOLATION_REPEATABLE_READ);
        ((DefaultTransactionDefinition) definition).setPropagationBehavior(PROPAGATION_SUPPORTS);


        TransactionStatus transaction = transactionManager.getTransaction(definition);

        try{
            Customer save = customerRepository.save(customer);
            transactionManager.commit(transaction);
            return save;
        }catch (Exception e){
            transactionManager.rollback(transaction);
            throw e;
        }
    }


}
